package com.sakura.动态规划;

public class Code343_整数拆分 {
    public static void main(String[] args) {
        System.out.println(new Code343_整数拆分().integerBreak2(5));
    }

    public int integerBreak1(int n) {
        if (n == 2) return 1;
        int ans = -1;
        for (int i = 1; i <= (n / 2); i++) {
            ans = Math.max(ans, Math.max(i * (n - i), i * integerBreak1(n - i)));
        }
        return ans;
    }

    public int integerBreak2(int n) {
        int[] dp = new int[n + 1];
        return f2(n, dp);
    }

    private int f2(int n, int[] dp) {
        if (n <= 2) return 1;
        // dp 表示：n 的最大乘积
        if (dp[n] != 0) {
            return dp[n];
        }
        int ans = -1;
        for (int i = 1; i <= (n / 2); i++) {
            ans = Math.max(ans, Math.max(i * (n - i), i * f2(n - i, dp)));
        }
        dp[n] = ans;
        return ans;
    }

    public int integerBreak3(int n) {
        if (n == 2) return 1;
        int[] dp = new int[n + 1];
        dp[1] = 1;
        for (int i = 2; i <= n; i++) {
            for (int j = 1; j <= i / 2; j++) {
                dp[i] = Math.max(dp[i], Math.max(j * (i - j), j * dp[i - j]));
            }
        }
        return dp[n];
    }
}
